package com.example.exp_5;

import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EFragment extends Fragment {
    LinearLayout list;
    ListView listfile;
    File[] files;
    String currentPath;
    TextView displayCurrentPath,fileName;
    int[] img = new int[]{R.drawable.ic_baseline_insert_drive_file_24,R.drawable.ic_baseline_folder_24};
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.list, container,false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savsaveInstanceState) {
        super.onViewCreated(view,savsaveInstanceState);
        list = view.findViewById(R.id.list);
        listfile = view.findViewById(R.id.listfile);
        displayCurrentPath = view.findViewById(R.id.display_currentpath);
        fileName = view.findViewById(R.id.file_name);
        init(Environment.getExternalStorageDirectory());
        listfile.setOnItemClickListener((adapterView, view1, i, l) -> {
            String folder = ((TextView) view1.findViewById(R.id.file_name)).getText().toString();
            try {
                File file = new File(currentPath + '/' + folder);
                init(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    public void init(File file) {
        files = file.listFiles();
        if (!files.equals(null)) {
            currentPath = file.getPath();
            displayCurrentPath.setText(file.getPath());
            List<Map<String, Object>> list = new ArrayList<>();
            for (File value : files) {
                Map<String, Object> maps = new HashMap<>();
                if (value.isFile()) {
                    maps.put("image", img[0]);
                } else {
                    maps.put("image", img[1]);
                }
                maps.put("filenames", value.getName());
                list.add(maps);
            }
            SimpleAdapter simple = new SimpleAdapter(getContext(), list, R.layout.single_file, new String[]{"image","filenames"}, new int[]{R.id.file_image, R.id.file_name});
            listfile.setAdapter(simple);
        }
    }
}
